
package com.android.image;

import java.io.File;
import java.lang.ref.SoftReference;
import java.net.URLEncoder;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.util.Log;

import com.android.vgongyi.R;

/**
 * thread pool manager
 */
public class TPManager implements VGongyiSetting {

    private static final String TAG = "TPManager";
    private static final int SIZE = 3;
    private static final int MAX_SIZE = 3;
    private ThreadPoolExecutor mPool;
    private static TPManager instance = new TPManager(); ;
    public static ConcurrentHashMap<String, SoftReference<Bitmap>> mImageCache = new ConcurrentHashMap<String, SoftReference<Bitmap>>();
    private static ImageIOThread ioThread;
    private Handler mHandler = new Handler();

    private TPManager() {
        mPool = new ThreadPoolExecutor(SIZE, MAX_SIZE, 1, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
        try {
            ioThread = ImageIOThread.getInstance();
        } catch (SdCardNotAvailableException e) {
            e.printStackTrace();
            //FIXME
        }
    }

    /**
     * get the static instance
     * @return
     */
    public static TPManager getInstance() {
        return instance;
    }

    /**
     * shutdown or stop the download and cache image thread
     */
    public void shutdownPool() {
        if (mPool != null) {
            mPool.shutdown();
            mPool = null;
        }
        if (ioThread != null) {
            ioThread.stopImageIO();
            ioThread = null;
        }
        if (mImageCache != null) {
            mImageCache.clear();
        }
    }

    /**
     * add task to thread pool
     * @param cache
     */
    public void addTask(CacheTask cache) {
        
    	String encodeUrl = URLEncoder.encode(cache.getUrl());
    	
    	cache.getImageView().setBackgroundResource(R.drawable.loading_image);

		Bitmap bitmap = getFromMemory(encodeUrl);
		if (bitmap != null) {
			showBitmap(cache, bitmap);
			return;
		}

		bitmap = getFromSdcard(cache);
		if (bitmap != null) {
			showBitmap(cache, bitmap);
			return;
		}
    	
        if (mPool != null) {
            cache.setHandler(mHandler);
            cache.setIOThread(ioThread);
            mPool.execute(cache);
        } else {
            if (DEBUG) {
                Log.e(TAG, "Pool,添加下载任务失败！");
            }
        }
    }
    
    /**
     * get bitmap from memory
     * @param url
     * @return
     */
    private Bitmap getFromMemory(String url) {
        SoftReference<Bitmap> sReference = TPManager.mImageCache.get(url);
        return sReference == null ? null : sReference.get();
    }
    
    public void cacheToMemory(String url, Bitmap bitmap){
        mImageCache.put(url, new SoftReference<Bitmap>(bitmap));
    }
    
    /**
     * get bitmap from sdcard
     * @param cache
     * @return
     */
    private Bitmap getFromSdcard(CacheTask cache) {
        String encodeUrl = URLEncoder.encode(cache.getUrl());
        String path = VGongyiApp.DEFAULT_SDCARD_PATH+encodeUrl;
        File file = new File(path);
        if (file.exists()) {
                Bitmap bitmap = BitmapFactory.decodeFile(path);
                cacheToMemory(encodeUrl, bitmap);
                return bitmap;
        }
        return null;
    }
    
    /**
     * show bitmap
     * @param bitmap
     */
    protected void showBitmap( CacheTask cache,  Bitmap bitmap) {

       cache.getImageView().setBackgroundDrawable(new BitmapDrawable(bitmap));
       
    }
    
}
